﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class McAccountsController : BaseController
    {
        private readonly McAccountsBLL _bll = new McAccountsBLL();
        private readonly McAccountRoleBLL _arBll = new McAccountRoleBLL();

        #region 列表

        [PermissionFilter]
        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Listing(int draw, int start, int length)
        {
            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                return null;
            }

            int order;
            int.TryParse(Request["order[0][column]"], out order);
            string direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "RoleName", "DisplayName", "Mobile", "UserName", "UserName" };
            string search = Request["search[value]"];
            int pageIndex = (start / length) + 1;
            int shopId = CurrentUser.ShopId;

            TableDataViewDto<McAccountDto> theList = _bll.GetPagingListForShop(draw, pageIndex, length, shopId.ToString(), SqlSafe(search), orderByColumns[order] + " " + direction, projectInfo, false);

            JsonResult jsonResult = Json(theList);
            jsonResult.MaxJsonLength = int.MaxValue;

            return jsonResult;
        }

        #endregion

        #region 分店账号列表

        [PermissionFilter]
        public ActionResult BranchList()
        {
            if (!CurrentUser.IsHeadquarters)
            {
                return View("List");
            }
            return View();
        }

        [HttpPost]
        public JsonResult BranchListing(int draw, int start, int length)
        {
            if (!CurrentUser.IsHeadquarters)
            {
                return null;
            }
            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                return null;
            }
            int order;
            int.TryParse(Request["order[0][column]"], out order);
            string direction = Request["order[0][dir]"];
            var orderByColumns = new[] { "DisplayName", "Mobile", "UserName", "UserName" };
            string search = Request["search[value]"];
            int pageIndex = (start / length) + 1;
            var subShopList = ShopsBLL.Instance.GetModelList("ParentShopId=" + CurrentUser.ShopId);
            var shopIds = string.Join(",", subShopList.Select(l => l.Id));
            var theList = _bll.GetPagingListForShop(draw, pageIndex, length, shopIds, SqlSafe(search), orderByColumns[order] + " " + direction, projectInfo, true);
            return Json(theList);
        }

        #endregion

        #region 添加

        public ActionResult Create()
        {
            InitiSet();

            var shopId = CurrentUser.ShopId;
            if (shopId < 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var model = new McAccountDto { ShopId = shopId };
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(FormCollection collection, McAccountDto model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var accountModel = new McAccounts
            {
                AccessFailedCount = 0,
                AccountType = 2, // 员工ID 非超管
                Created = DateTime.Now,
                CreatedBy = CurrentUser.AccountId,
                DisplayName = model.DisplayName,
                IsDelete = false,
                IsMagAccount = false,
                LockoutEnabled = false,
                LockoutUntil = DateTime.Now,
                Mobile = model.Mobile,
                PasswordHash = EncryptionLib.Encrypt(model.PasswordHash),
                ShopId = model.ShopId,
                Updated = DateTime.Now,
                UpdatedBy = CurrentUser.AccountId,
                UserName = model.UserName,
                MxProjectInfoId = projectInfo.Id,
                MxWechatInfoUserId = 0
            };

            var result = _bll.Add(accountModel);

            if (result <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
            if (!string.IsNullOrEmpty(model.Mobile))
            {
                var sendContent = string.Format(ConfigurationManager.AppSettings["SendContent"], model.UserName, model.PasswordHash);
                SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.McMag, CommonEnum.SmsRecordUserActionSource.AddDelivery);
            }
            var arModel = new McAccountRole {AccountId = result, RoleId = model.RoleId, IsDelete = false};
            _arBll.Add(arModel);
            return RedirectToAction("List", "McAccounts");
        }

        #endregion

        #region 修改

        public ActionResult Update(int? id)
        {
            InitiSet();

            var accountId = 0;
            if (id == null || id <= 0)
            {
                accountId = CurrentUser.AccountId;
                if(accountId == 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            else
            {
                accountId = (int)id;
            }

            var localProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (localProjectInfo == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var model = _bll.GetModelWithRoleInfo(accountId, localProjectInfo);

            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            ViewBag.CurrentUser = CurrentUser;

            return View(model);
        }

        [HttpPost]
        public ActionResult Update(FormCollection collection, McAccountDto model)
        {
            if (model == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var oriAccount = _bll.GetModel(model.AccountId);
            var oldMobile = oriAccount.Mobile;
            oriAccount.DisplayName = model.DisplayName;
            oriAccount.Mobile = model.Mobile;
            oriAccount.PasswordHash = string.IsNullOrEmpty(model.PasswordHash) ? oriAccount.PasswordHash : EncryptionLib.Encrypt(model.PasswordHash);
            oriAccount.UpdatedBy = CurrentUser.AccountId;
            oriAccount.Updated = DateTime.Now;

            var oriAccountRole = McAccountRoleBLL.Instance.GetModelByAccountId(model.AccountId);
            oriAccountRole.RoleId = model.RoleId;
            
            bool accountResult = _bll.Update(oriAccount);
            if (accountResult)
            {
                //更改手机号或者密码，发送短信
                if (CurrentUser.RoleId == (int) CommonEnum.McAccountRole.Boss && !string.IsNullOrEmpty(model.Mobile) && (!string.IsNullOrEmpty(model.PasswordHash) || oriAccount.Mobile != oldMobile))
                {
                    var sendContent = string.Format(ConfigurationManager.AppSettings["SendContent"], oriAccount.UserName, EncryptionLib.Decrypt(oriAccount.PasswordHash));
                    SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.McMag, CommonEnum.SmsRecordUserActionSource.ModifyDelivery);
                }
            }
            bool accRoleResult = McAccountRoleBLL.Instance.Update(oriAccountRole);

            if (accountResult && accRoleResult)
                return RedirectToAction("List", "McAccounts");

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 分店账号修改

        public ActionResult BranchUpdate(int id)
        {
            InitiSet();
            if (id <= 0 || !CurrentUser.IsHeadquarters)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var localProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (localProjectInfo == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var model = _bll.GetModelWithRoleInfo(id, localProjectInfo);
            if (model == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var checkModel = ShopsBLL.Instance.GetModelList("Id=" + model.ShopId + " and ParentShopId=" + CurrentUser.ShopId);
            if (checkModel.Count == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ViewBag.CurrentUser = CurrentUser;
            return View(model);
        }

        [HttpPost]
        public ActionResult BranchUpdate(FormCollection collection, McAccountDto model)
        {
            if (model == null || !CurrentUser.IsHeadquarters)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var oriAccount = _bll.GetModel(model.AccountId);
            var checkModel = ShopsBLL.Instance.GetModelList("Id=" + oriAccount.ShopId + " and ParentShopId=" + CurrentUser.ShopId);
            if (checkModel.Count == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var oldMobile = oriAccount.Mobile;
            oriAccount.DisplayName = model.DisplayName;
            oriAccount.Mobile = model.Mobile;
            oriAccount.PasswordHash = string.IsNullOrEmpty(model.PasswordHash) ? oriAccount.PasswordHash : EncryptionLib.Encrypt(model.PasswordHash);
            oriAccount.UpdatedBy = CurrentUser.AccountId;
            oriAccount.Updated = DateTime.Now;

            var oriAccountRole = McAccountRoleBLL.Instance.GetModelByAccountId(model.AccountId);
            oriAccountRole.RoleId = model.RoleId;

            bool accountResult = _bll.Update(oriAccount);
            if (accountResult)
            {
                //更改手机号或者密码，发送短信
                if (CurrentUser.RoleId == (int)CommonEnum.McAccountRole.Boss && !string.IsNullOrEmpty(model.Mobile) && (!string.IsNullOrEmpty(model.PasswordHash) || oriAccount.Mobile != oldMobile))
                {
                    var sendContent = string.Format(ConfigurationManager.AppSettings["SendContent"], oriAccount.UserName, EncryptionLib.Decrypt(oriAccount.PasswordHash));
                    SmsRecordBLL.Instance.SendSms(model.Mobile, sendContent, CommonEnum.SmsRecordSendFrom.McMag, CommonEnum.SmsRecordUserActionSource.ModifyDelivery);
                }
            }
            bool accRoleResult = McAccountRoleBLL.Instance.Update(oriAccountRole);

            if (accountResult && accRoleResult) 
            {
                return RedirectToAction("BranchList", "McAccounts");
            }

            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }

        #endregion

        #region 删除
        
        [HttpPost]
        public JsonResult Delete()
        {
            string ids = Request["doIds"];
            bool result = _bll.DeleteList(ids);
            var accountRole = _arBll.GetModelByAccountId(int.Parse(ids));
            bool arResult = _arBll.DeleteList(accountRole.Id.ToString());

            return Json(result && arResult);
        }

        #endregion

        #region 账户唯一验证

        /// <summary>
        /// 检查重复数据
        /// </summary>
        [HttpPost]
        public JsonResult ValidateUserName(string userName, int accountId)
        {
            var resultMessage = _bll.CheckUserNameAvailable(userName, accountId);
            return Json(resultMessage);
        }

        #endregion

        /// <summary>
        /// 所有订单数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetCount()
        {
            int shopId = CurrentUser.ShopId;
            var count = McAccountsBLL.Instance.GetOneShopAllStaffs(shopId).Count;
            return Json(count);
        }

        #region Private Functions 自用函数

        private void InitiSet()
        {
            List<SelectListItem> lsRoles =
                McRolesBLL.Instance.GetModelList().Select(model => new SelectListItem
                {
                    Value = model.Id.ToString(),
                    Text = model.Name
                }).ToList();
            ViewBag.Roles = lsRoles;
        }

        #endregion
    }
}